package jp.ac.u_tokyo.dch.dao.schema;

import jp.ac.u_tokyo.dch.core.db.CustomPreparedStatement;
import jp.ac.u_tokyo.dch.core.db.CustomResultSet;
import jp.ac.u_tokyo.dch.core.db.DBConnection;
import jp.ac.u_tokyo.dch.core.exceptions.DBException;
import jp.ac.u_tokyo.dch.view.Constants;
/**
* @version 1.1
*/
public class TypeItemsDao {

	/**
	 * DBコネクションオブジェクト
	 */
	private DBConnection dbconn = null;

	/**
	 * 生成者
	 * @param DBコネクションオブジェクト
	 */
	public TypeItemsDao(DBConnection dbconn){
		this.dbconn = dbconn;
	}

	/**
	 * データタイプを取得する
	 * @param schemaid
	 * @param fieldKey
	 * @return
	 * @throws DBException
	 */
	public String selectOptions(int schemaid, String fieldKey)  throws DBException {

		StringBuilder options = new StringBuilder();
		CustomPreparedStatement ps = null;
		CustomResultSet rs = null;
		try{
			String query = "SELECT optionvalue FROM type_items WHERE schemaid = ? and fieldkey = ? order by id";

			ps = dbconn.prepareStatement(query);

			ps.setInt(1, Integer.valueOf(schemaid));
			ps.setString(2, fieldKey);

			rs = ps.executeQuery();
			while (rs.next()){

				options.append(rs.getString("optionvalue"));
				options.append(Constants.OPTION_DEL);
			}
			options.deleteCharAt(options.length() - 1);
		}catch(DBException dbe){
			throw dbe;
		}finally{
			if(ps != null) ps.close();
			if(rs != null) rs.close();
		}
		return options.toString();
	}

	/**
	 * 削除する
	 * @param schemaid スキーマID
	 * @return 削除件数
	 * @throws DBException 例外
	 */
	public int delete(int schemaid) throws DBException {

		CustomPreparedStatement ps = null;
		int result = 0;
		try{
			String query = "DELETE FROM type_items WHERE schemaid = ? ";

			ps = dbconn.prepareStatement(query);
			ps.setInt(1, schemaid);
			result = ps.executeUpdate();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			if(ps != null) ps.close();
		}
		return result;
	}

	/**
	 * 挿入する
	 * @param schemaid スキーマID
	 * @param options オプション
	 * @param fieldKey 項目キー
	 * @return 挿入件数情報
	 * @throws DBException 例外
	 */
	public int[] insert(int schemaid, String options, String fieldKey) throws DBException {

		CustomPreparedStatement ps = null;
		int result[] = null;

		try{
			String query = "INSERT INTO type_items (schemaid,fieldkey,optionvalue) VALUES (?,?,?)";

			ps = dbconn.prepareStatement(query);

			for (String option : options.split(Constants.OPTION_DEL)) {
				int index = 1;
				ps.setInt(index++, schemaid);
				ps.setString(index++, fieldKey);
				ps.setString(index++, option);

				ps.addBatch();
			}
			result = ps.executeBatch();
		}catch(DBException dbe){
			throw dbe;
		}finally{
			if(ps != null) ps.close();
		}
		return result;
	}
}
